using SimpleCore;
using UnityEngine;

namespace SFw.Core.ObjComp
{
    public class EffectComp : MonoBehaviour
    {
        public float beginEffectDuration;
        public float endEffectDuration;
        public bool autoDestroyWhenHide = true;
        
        private GameObject _beginEffect;
        private GameObject _loopEffect;
        private GameObject _endEffect;
        
        private void Awake()
        {
            _beginEffect = transform.Find("begin").gameObject;
            _loopEffect = transform.Find("loop").gameObject;
            _endEffect = transform.Find("end").gameObject;

            ResetEffect();
        }

        void ResetEffect()
        {
            CheckNotNullThenSetActive(_beginEffect, false);
            CheckNotNullThenSetActive(_loopEffect, false);
            CheckNotNullThenSetActive(_endEffect, false);
        }

        void CheckNotNullThenSetActive(GameObject obj, bool active)
        {
            if(obj.Equals(null)) return;
            obj.SetActive(active);
        }

        public void Show()
        {
            ResetEffect();
            
            gameObject.SetActive(true);
            
            CheckNotNullThenSetActive(_beginEffect, true);
            TimeTool.WaitToDo(beginEffectDuration, () =>
            {
                CheckNotNullThenSetActive(_beginEffect, false);
                CheckNotNullThenSetActive(_loopEffect, true);
            });
        }

        public void Hide()
        {
            ResetEffect();
            
            CheckNotNullThenSetActive(_endEffect, true);
            TimeTool.WaitToDo(endEffectDuration, () =>
            {
                CheckNotNullThenSetActive(_endEffect, false);
                gameObject.SetActive(false);

                if (autoDestroyWhenHide)
                {
                    Destroy(this);
                }
            });
        }

#if UNITY_EDITOR
        private void Update()
        {
            if (Input.GetKey(KeyCode.A))
            {
                Show();
            }
            else if (Input.GetKey(KeyCode.D))
            {
                Hide();
            }
        }
#endif
    }
}